#include "Settings.h"
#include <fstream>
#include <iostream>


std::string Settings::fileName_ = "resources/settings.txt";
const std::string Settings::ERROR_VALUE_ = "NO_SUCH_KEY";

Settings::Settings()
{
  load();
}

Settings& Settings::getInstance()
{
  static Settings instance_;
  
  return instance_;
  
}

void Settings::setFileName(const std::string& fileName)
{
  fileName_ = fileName;
}

int Settings::load()
{
  std::ifstream f;
  f.open(fileName_.c_str());
  if (f == 0)
  {
    f.close();
    return 1;
  }
   
  std::string key;
  std::string value;
  while(!f.eof())
  {
    f >> key >> value;
    codes_[key] = value;
  }

  f.close();
   
  return 0;
}

int Settings::save()
{
  std::ofstream f;
  f.open(fileName_.c_str());
  if (f == 0)
  {
    f.close();
    return 1;
  }
  for (std::map<std::string, std::string>::iterator it = codes_.begin(); it != codes_.end(); ++it)
  {
    f << it->first << " " << it->second;
  }
  return 0;
  f.close();
}
  
void Settings::add(const std::string &key, const std::string &value)
{
   codes_[key] = value;
}

void Settings::del(const std::string &key)
{
  codes_.erase(key);
}

  
void Settings::set(const std::string &key, const std::string &value)
{
  if (codes_.find(key) == codes_.end())
  {
    return;
  }
  codes_[key] = value;
}


const std::string& Settings::get(const std::string &key)
{
  if (codes_.find(key) == codes_.end())
  {
    return ERROR_VALUE_;
  }
  return codes_[key];
}

